package com.wu.store.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.wu.store.annotation.AdminUser;
import com.wu.store.annotation.CurrentUser;
import com.wu.store.common.util.MessageEntity;
import com.wu.store.common.util.PageUtils;
import com.wu.store.dao.GoodsDao;
import com.wu.store.entity.*;
import com.wu.store.service.CategoryService;
import com.wu.store.service.GoodsService;
import com.wu.store.service.impl.GoodsServiceImpl;
import org.apache.commons.lang3.StringUtils;
import org.apache.ibatis.annotations.Param;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.UUID;

@RestController
@RequestMapping("/goods")
public class GoodsController {
	private String rootDir = System.getProperty("user.dir");
	@Autowired
	private GoodsService goodsService;


	@Autowired
	private GoodsDao goodsDao;

	@Autowired
	private CategoryService categoryService;


	@RequestMapping("/list")
	public MessageEntity getList(@CurrentUser User user, GoodsParams goodsParams) throws Exception {
		boolean isAdmin = user.getRole() == 1;
		if (isAdmin) {
			goodsParams.setStatus(null);
		} else {
			goodsParams.setStatus(1);
			goodsParams.setUid(user.getId());
		}
		List<Goods> list = goodsService.getList(goodsParams);
		PageInfo<Goods> goodsListPageInfo = new PageInfo<>(list, 1);
		return new MessageEntity.Builder().success(true).data(PageUtils.getPageResult(goodsListPageInfo)).create();
	}

	@RequestMapping("/info")
	public MessageEntity getInfo(@CurrentUser User user, Long id, Long cartId) throws Exception {
		if (id == null) {
			throw new Exception("id必需");
		}
		Cart cart = null;
		if (cartId != null) {
			cart = new Cart();
			cart.setUid(user.getId());
			cart.setId(cartId);
			cart.setGoodsId(id);
		}
		return new MessageEntity.Builder().success(true).message("获取成功").data(goodsService.getGoodsInfo(id, cart)).create();
	}

	@RequestMapping("/isNameValid")
	public MessageEntity isNameValid(Goods goods) throws Exception {

		if (StringUtils.isEmpty(goods.getName())) {
			throw new Exception("name必需");
		}
		return new MessageEntity.Builder().success(goodsService.isNameValid(goods)).message("商品名称可用").create();
	}

	@RequestMapping("/save")
	public MessageEntity saveGoods(@RequestParam(value = "imgList") String str, Goods originGoods) throws Exception {
		List<Img> imgList = JSON.parseArray(str, Img.class);
		GoodsWithImgList goods = new GoodsWithImgList();
		BeanUtils.copyProperties(originGoods, goods);
		goods.setImgList(imgList);
		boolean flag = goodsService.isNameValid(goods);
		if (goods.getCategoryId() == null) {
			String categoryName = goods.getCategoryName();
			if (StringUtils.isEmpty(categoryName)) {
				throw new Exception("请选择商品类别");
			}
			Category category = new Category();
			category.setName(categoryName);
			boolean isNameValid = categoryService.isNameValid(category);
			if (isNameValid) {
				Long categoryId = categoryService.save(category);
				goods.setCategoryId(categoryId);
			}
		}
		if (flag) {
			goodsService.save(goods);
		}
		return new MessageEntity.Builder().success(true).message("操作成功").create();
	}

	@RequestMapping("/delete")
	public MessageEntity deleteGoods(@AdminUser Boolean isAdmin, Long id) throws Exception {
		if (id == null) {
			throw new Exception("id必需");
		}
		return new MessageEntity.Builder().success(goodsService.delete(id)).message("操作成功").create();
	}

	@RequestMapping("/hot/list")
	public MessageEntity getRecommendList(@CurrentUser User user) {
		List<Goods> recommendList = goodsService.getHotList();
		return new MessageEntity.Builder().success(true).data(recommendList).message("获取成功").create();
	}

	@RequestMapping("/init")
	public MessageEntity init(String del) throws Exception {
		File targetDir = new File(rootDir + "/goodsImg/");
		if (!targetDir.exists() || !targetDir.isDirectory()) {
			boolean mkdir = targetDir.mkdir();
			if (!mkdir) {
				throw new Exception("创建文件夹失败");
			}
		}
		String[] files = targetDir.list();
		if (files == null || files.length == 0) {
			return new MessageEntity.Builder().success(true).message("这是个空文件夹").create();
		}
		List<String> fileList = new ArrayList<>(Arrays.asList(files));
		GoodsParams goodsParams = new GoodsParams();
		goodsParams.setPage(1);
		goodsParams.setSize(Integer.MAX_VALUE);
		List<Goods> goodsList = goodsService.getList(goodsParams);
		for (Goods goods : goodsList) {
			if (StringUtils.isNotEmpty(goods.getImg())) {
				String fileName = goods.getName() + "_" + UUID.randomUUID().toString().substring(0, 4);
				File file = new File(rootDir + goods.getImg());
				String ext = getExt(goods.getImg());
				if (file.exists()) {
					fileList.remove(file.getName());
					String targetPath = "/goodsImg/" + fileName + ext;
					File toFile = new File(rootDir + targetPath);
					boolean flag = file.renameTo(toFile);
					if (flag) {
						goods.setImg(targetPath);
						goodsDao.update(goods);
					}
				}
			}

			List<Img> imgList = goodsDao.getImgList(goods.getId());
			for (Img img : imgList) {
				String fileName = goods.getName() + "_" + UUID.randomUUID().toString().substring(0, 4);
				File file = new File(rootDir + img.getImg());
				String ext = getExt(img.getImg());
				if (file.exists()) {
					fileList.remove(file.getName());
					String targetPath = "/goodsImg/" + fileName + ext;
					File toFile = new File(rootDir + targetPath);
					boolean flag = file.renameTo(toFile);
					if (flag) {
						img.setImg(targetPath);
						int affectedRow = goodsDao.updateImgItem(img);
						if (affectedRow == 0) {
							toFile.renameTo(file);
							throw new Exception("更新失败");
						}
					}
				}
			}
		}
		if ("1".equals(del)) {
			for (String path : fileList) {
				File file = new File(rootDir + "/goodsImg/" + path);
				boolean delete = file.delete();
				if (!delete){
					throw new Exception("删除失败");
				}
			}
		}
		return new MessageEntity.Builder().success(true).message("更新商品图片命名" + ("1".equals(del) ? "且删除多余图片" : "") + "成功").create();
	}

	private String getExt(String filename) {
		int index = filename.lastIndexOf(".");

		if (index == -1) {
			return null;
		}
		return filename.substring(index);
	}

}
